import { UseGuards } from '@nestjs/common';
import {
  MessageBody,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
} from '@nestjs/websockets';
import { Server } from 'socket.io';
import { WsJwtAuthGuard } from 'src/auth/guards/ws-jwt-auth.guard';
import ErrorExcption from 'src/error/ErrorExcption';
import { UserService } from 'src/modules/user/user.service';
import { MessageData, Status } from './chat.interface';

@WebSocketGateway(4001, {
  allowEIO3: true,
  cors: {
    origin: /.*/,
    credentials: true,
  },
})
export class ChatGateway {
  constructor(private readonly userService: UserService) {}
  @WebSocketServer()
  server: Server;

  // @UseGuards(WsJwtAuthGuard)
  // @SubscribeMessage('clientToServer')
  // async clientToServer(
  //   @MessageBody() clientData: MessageData,
  // ): Promise<MessageData> {
  //   console.log('客户消息: ', clientData.content);

  //   return { content: '你好，我是小帅，很高兴为你服务！' };
  // }

  // @UseGuards(WsJwtAuthGuard)
  // @Cron(CronExpression.EVERY_10_SECONDS)
  // async sayHi() {
  //   this.server.emit('serverToClient', { content: '你还在么？' });
  //   // this.server.sockets.socketsJoin()
  // }

  // @UseGuards(WsJwtAuthGuard)
  @SubscribeMessage('join')
  async join(@MessageBody() data: MessageData) {
    try {
      console.log('join', data);
      this.server.socketsJoin(data.roomid);
      this.server.to(data.roomid).emit('newjoin', '');
      return { event: 'toClient', data: '成功加入' };
    } catch (error) {
      throw new ErrorExcption(error, 400);
    }
  }

  // @SubscribeMessage('hello2')
  // hello2(@MessageBody() data: any): any {
  //   // console.log('收到消息 client:', client);
  //   // client.send(JSON.stringify({ event: 'tmp', data: '这里是个临时信息' }));
  //   return { event: 'hello2', data: data };
  // }
  // @UseGuards(WsJwtAuthGuard)
  @SubscribeMessage('sendToServer')
  send(@MessageBody() data: MessageData) {
    this.server.to(data.roomid).emit('sendToClient', data.content);
  }

  // @UseGuards(WsJwtAuthGuard)
  @SubscribeMessage('leave')
  leave(@MessageBody() data: MessageData): any {
    console.log('leaveRoom', data);
    this.server.socketsLeave(data.roomid);
    this.server.to(data.roomid).emit('toClient', '离开房间');
    // return { content: 'leave sucess', status: Status.success };
  }

  @SubscribeMessage('player')
  play(@MessageBody() data: MessageData) {
    console.log('player', data);
    this.server.to(data.roomid).emit(data.type, data.content);
  }

  @SubscribeMessage('heartBeat')
  heartBeat(@MessageBody() data: string) {
    if (data === 'ping') {
      // this.server.emit('heartbeat', 'pong');
      // this.server.sockets.emit('heartbeat', 'pong');
      return { event: 'heartbeat', data: 'pong' };
    }
  }
}
